﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EntityFramework.Extensions;
using Abp.UI;
using Abp.Domain.Repositories;
using Omu.ValueInjecter;
using App.BaseObject;
using App.Configuration.Dto;

namespace App.Configuration
{
    public class DictionaryAppService : AppServiceBase, IDictionaryAppService
    {
        protected IRepository<Dictionary> _dicRepository;

        public DictionaryAppService(
            IRepository<Dictionary> dicRepository)
        {
            _dicRepository = dicRepository;
        }

        public async Task SaveDictionarys(BulkDto<DictionaryDto> dto)
        {
            //批量插入
            foreach (var row in dto.InsertedRows)
            {
                if (await _dicRepository.CountAsync(b => b.Key == row.Key) > 0)
                {
                    throw new UserFriendlyException(string.Format("名为【{0}】的字典已经存在！", row.Key));
                }
                else
                {
                    var entity = new Dictionary();
                    entity.InjectFrom(row);
                    entity.TenantId = AbpSession.TenantId;
                    await _dicRepository.InsertAsync(entity);
                }
            }
            //批量更新
            foreach (var row in dto.UpdatedRows)
            {
                var entity = await _dicRepository.GetAsync(row.Id.Value);
                entity.InjectFrom(row);
            }

            //删除
            foreach (var row in dto.DeletedRows)
            {
                if (row.Id.HasValue)
                    await _dicRepository.DeleteAsync(row.Id.Value);
            }
        }

        public async Task<Dictionary> GetDictionaryAsync(int id)
        {
            return await _dicRepository.FirstOrDefaultAsync(id);
        }

        public async Task<List<Dictionary>> GetAll()
        {
            return await _dicRepository.GetAllListAsync();
        }

        public async Task<Dictionary<string, int>> GetDictionaryText(string key)
        {
            var entity = await _dicRepository.FirstOrDefaultAsync(s => s.Key == key);
            if (entity != null)
            {
                var result = new Dictionary<string, int>();
                int i = 0;
                foreach (var item in entity.Dictionarys.Split(','))
                {
                    result.Add(item, i);
                    i++;
                }

                return result;
            }

            return new Dictionary<string, int>();
        }
    }
}
